package top.fangw.common.flyway.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.Location;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: fgw
 * @createDate: 2024/1/11
 */
@Slf4j
public class CreateTable {


    /**
     * @param url             数据库连接地址
     * @param username        数据库用户名
     * @param password        数据库密码
     * @param version         版本号
     * @param tenantId        租户ID
     * @param dataBaseMap     数据库名称
     * @param renameTableName 是否重命名表名称
     */
    public void createTable(String url, String username, String password, String version, String tenantId, Map<String, String> dataBaseMap,  Boolean renameTableName) {
        dataBaseMap.forEach((k, v) -> {
            try {
                String sqlContent = getStringFromResource(v + "/V" + version + "__init.sql");
                // 替换数据库表名称
                var ref = new Object() {
                    String s = sqlContent.trim();
                };
                if (renameTableName) {
                    String string = getStringFromResource(v + "/temp/default.txt");
                    Set<String> collect = Arrays.stream(string.split(",")).collect(Collectors.toSet());
                    collect.forEach(item -> {
                        ref.s = ref.s.replaceAll(item +"`", item + "_" + tenantId +"`");
                    });
                }
                log.info("修改后SQL内容：{}", ref.s);
                String folderPath = getClass().getClassLoader().getResource(v).getPath();
                Path filePath = Path.of(folderPath + "/temp/V" + version + "__temp__init.sql");
                Files.writeString(filePath, ref.s, StandardOpenOption.CREATE);

                Flyway flyway = Flyway.configure()
                        .dataSource(String.format(UrlFormatUtil.formatTableUrl(url), k), username, password)
                        .locations(new Location(v + "/temp"))
                        .defaultSchema(k)
                        .load();
                flyway.migrate();
                File file = new File(folderPath + "/temp/V" + version + "__temp__init.sql");
                if (file.exists()) {
                    file.delete();
                    log.info("删除文件{}成功", folderPath + "/temp/V" + version + "__temp__init.sql");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private String getStringFromResource(String path) {
        InputStream inputStream = null;
        StringWriter writer = null;
        String text = null;
        try {
            inputStream = getClass().getClassLoader().getResourceAsStream(path);
            writer = new StringWriter();
            IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8.name());
            text = writer.toString();
            inputStream.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return text;
    }
}
